﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using JPW.OnlinePaperSubmissionSystem.Project.Dto;
using Kendo.DynamicLinq;
using System.Data.Entity;
namespace JPW.OnlinePaperSubmissionSystem.Project
{

    // [AbpAuthorize(AppPermissions.Pages_Tenant_Manuscript)]
    public class ManuscriptAppService : AbpZeroTemplateAppServiceBase, IManuscriptAppService
    {
        private readonly IRepository<Manuscript, long> _manuscriptRepository;
        private readonly IRepository<Audit, long> _auditRepository;
        private readonly IRepository<ManuscriptChecked, long> _manuscriptCheckedRepository;
        public ManuscriptAppService(
            IRepository<Audit, long> auditRepository,
            IRepository<Manuscript, long> manuscriptRepository,
            IRepository<ManuscriptChecked, long> manuscriptCheckedRepository
            )
        {
            _auditRepository = auditRepository;
            _manuscriptRepository = manuscriptRepository;
            _manuscriptCheckedRepository = manuscriptCheckedRepository;
        }

        public DataSourceResult KendoGetManuscripts(DataSourceRequest input)
        {
            List<Manuscript> list = new List<Manuscript>();
            var nextUserID = input.Filter.Filters.FirstOrDefault(x => x.Field == "nextUserID");
            if (nextUserID != null)
            {
                List<Filter> filters = input.Filter.Filters.ToList();
                filters.RemoveAt(0);
                input.Filter.Filters = filters;
                long nextUid = Convert.ToInt64(nextUserID.Value);
                var query1 = _manuscriptCheckedRepository.GetAll().Where(x => x.NextUserID == nextUid);
                foreach (var item in query1)
                {
                    list.Add(item.Manuscript);
                }
            }

            if (input.Filter.Filters.Count() > 0)
            {
                var query1 = _manuscriptRepository
            .GetAll()
            .OrderByDescending(p => p.Id).ToDataSourceResult(0, 0, input.Sort, input.Filter);
                foreach (Manuscript item in query1.Data)
                {
                    list.Add(item);
                }
                return list.MapTo<List<ManuscriptListDto>>().AsQueryable().ToDataSourceResult(input.Take, input.Skip, input.Sort, null);
            }
            else
            {
                var manuscripts = _manuscriptRepository
             .GetAll()
             .OrderByDescending(p => p.Id)
             .MapTo<List<ManuscriptListDto>>().AsQueryable()
             .ToDataSourceResult(input.Take, input.Skip, input.Sort, null);
                return manuscripts;
            }
        }
        public ListResultOutput<ManuscriptListDto> GetManuscripts(GetManuscriptInput input)
        {
            var manuscripts = _manuscriptRepository
            .GetAll()
            //.WhereIf(
            //    !input.Filter.IsNullOrEmpty(),
            //    p => p.Name.Contains(input.Filter) ||
            //            p.Code.Contains(input.Filter) 
            //||p.Performance==Convert.ToInt32(input.Filter)
            //)
            .OrderByDescending(p => p.Id)
            .ToList();

            return new ListResultOutput<ManuscriptListDto>(manuscripts.MapTo<List<ManuscriptListDto>>());
        }
        public async Task<ListResultOutput<ManuscriptListDto>> GetManuscriptsAsync()
        {
            var query = await _manuscriptRepository.GetAll().OrderByDescending(p => p.Id).ToListAsync();

            return new ListResultOutput<ManuscriptListDto>(query.MapTo<List<ManuscriptListDto>>());

        }

        //  [AbpAuthorize(AppPermissions.Pages_Tenant_Manuscript_Delete)]
        public async Task DeleteManuscript(IdInput input)
        {
            await _manuscriptRepository.DeleteAsync(input.Id);
        }

        public async Task CreateOrUpdateManuscript(CreateOrUpdateManuscriptInput input)
        {
            if (input.Manuscript.ID.HasValue)
            {
                await UpdateManuscriptAsync(input);
            }
            else
            {
                await CreateManuscriptAsync(input);
            }
        }
        //  [AbpAuthorize(AppPermissions.Pages_Tenant_Manuscript_Create)]
        public async Task CreateManuscriptAsync(CreateOrUpdateManuscriptInput input)
        {
            var manuscript = input.Manuscript.MapTo<Manuscript>();
            manuscript.UserId = AbpSession.UserId;
            await _manuscriptRepository.InsertAsync(manuscript);
        }
        //  [AbpAuthorize(AppPermissions.Pages_Tenant_Manuscript_Update)]
        public async Task UpdateManuscriptAsync(CreateOrUpdateManuscriptInput input)
        {
            var manuscript = input.Manuscript.MapTo<Manuscript>();
            await _manuscriptRepository.UpdateAsync(manuscript);
        }
        //  [AbpAuthorize(AppPermissions.Pages_Tenant_Manuscript_Update)]
        public async Task<GetManuscriptForEditOutput> GetManuscriptForEdit(NullableIdInput input)
        {
            Manuscript manuscript = null;
            if (input.Id.HasValue) //Editing existing role?
            {
                manuscript = await _manuscriptRepository.FirstOrDefaultAsync(input.Id.Value);
            }
            return new GetManuscriptForEditOutput
            {
                Manuscript = manuscript.MapTo<ManuscriptEditDto>()


            };
        }
        public ListResultOutput<AuditListDto> GetAudit(long id)
        {

            var auditId = from n in _manuscriptCheckedRepository.GetAll()
                          where n.ManuscriptId == id
                          select n.AuditId;
            List<long?> ids = auditId.ToList();
            var query = _auditRepository.GetAll().Where(x => ids.Contains(x.Id));
            return new ListResultOutput<AuditListDto>(query.MapTo<List<AuditListDto>>());


        }

        ///根据稿件ID再获取该所有审核意见的方法
        //public ListResultOutput<AuditListDto> GetAudit(IdInput input)
        //{
        //    List<Audit> Audits = new List<Audit>();
        //    var query = from n in _manuscriptCheckedRepository.GetAll()
        //                where n.ManuscriptId == input.Id
        //                select n;
        //    //var query = _manuscriptCheckedRepository.GetAll().Where(x => x.ManuscriptId == input.Id).ToList();
        //    foreach (var item in query)
        //    {
        //        Audits.Add(item.Audit);
        //    }
        //    return new ListResultOutput<AuditListDto>(Audits.MapTo<List<AuditListDto>>()); 
        //}


    }
}

